package com.zkca.xf.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.zkca.xf.ConstantsXF;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.SmsBean;
import com.zkca.xf.model.javabean.UserBean_W;
import com.zkca.xf.model.javabean.uploadbean.RequestSms;
import com.zkca.xf.model.javabean.uploadbean.RequestUser;
import com.zkca.xf.presenter.LoginCodePresenter;
import com.zkca.xf.utils.DeviceUtils;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.Md5Util;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.LoginCodeView;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

public class Activity_Login_Code extends BaseTitleActivity implements LoginCodeView {


    @BindView(R.id.editText_name)
    EditText editTextName;
    @BindView(R.id.line_user)
    LinearLayout lineUser;
    @BindView(R.id.text_fenge)
    TextView textFenge;
    @BindView(R.id.editText_psw)
    EditText editTextPsw;
    @BindView(R.id.timebutton)
    Button timeButton;
    @BindView(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    @BindView(R.id.login)
    Button login;

    //不更新的标志
    public static final int SHOW_NO_UPDATE_DIALOG = 1;
    //更新的标志
    public static final int SHOW_UPDATE_DIALOG = 2;

    private static boolean isExit = false;
    @BindView(R.id.servers)
    TextView servers;

    private String[] permissions2 = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String[] permissions = {Manifest.permission.READ_PHONE_STATE};
    private LoginCodePresenter loginCodePresenter;

    private RequestSms requestSms;
    private RequestUser requestUser;
    MyCountDownTimer myCountDownTimer;

    private String mobileToken;

    private int mobileType=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity__login__code);
        ButterKnife.bind(this);


        // mobileToken= DeviceUtils.getDeviceId(mContext);

       // LogUtil.e("12312",mobileToken+",.,.");

        setTitleText("登陆");
        String ip_port = SPUtil.getString(mContext, Constants_SP.SERVER_ADDRESS);
        servers.setText("您的访问路径为"+ip_port+"        点击修改");
        servers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shouJinggao();
            }
        });
        loginCodePresenter = new LoginCodePresenter(this, this);
        //new倒计时对象,总共的时间,每隔多少秒更新一次时间
        myCountDownTimer = new MyCountDownTimer(120000, 1000);
        //设置Button点击事件触发倒计时
        timeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                startActivity(new Intent(Activity_Login_Code.this, XunjianActivity.class));
                if (TextUtils.isEmpty(editTextName.getText())) {
                    ToastUtils.show(Activity_Login_Code.this, "请输入手机号");
                } else if (!isChinaPhoneLegal(editTextName.getText().toString())) {
                    ToastUtils.show(Activity_Login_Code.this, "号码不符合手机号码格式");
                } else {

                    initRequSMSData();
                    loginCodePresenter.getSMS(requestSms);
                }

            }
        });


        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(editTextName.getText()) && TextUtils.isEmpty(editTextPsw.getText())) {
                    ToastUtils.show(Activity_Login_Code.this, "手机号与验证码不可为空");
                } else {
                    myCountDownTimer.cancel();
                    myCountDownTimer.onFinish();
                    initRequsUserData();
                    loginCodePresenter.logInByCode(requestUser);
                }

            }
        });


//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.app_name, null);
//        final String s = convertIconToString(bitmap);
//        LogUtil.e("111",s);
//
//
//        RxPermissions rxPermissions = new RxPermissions(Activity_Login_Code.this);
//        rxPermissions.request(permissions2)
//                .subscribe(new Consumer<Boolean>() {
//                    @Override
//                    public void accept(@NonNull Boolean granted) throws Exception {
//                        //同意授权
//                        if (granted) {
//                            if (ActivityCompat.checkSelfPermission(Activity_Login_Code.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                                ToastUtils.show(Activity_Login_Code.this, "请添加读写权限");
//                                return;
//                            }
//                            saveFile(s);
//                        } else {//拒绝
//                            ToastUtils.show(Activity_Login_Code.this, "请添加读写权限");
//                        }
//                    }
//                });
//
//
//        File file=new File("/storage/emulated/0/string_s.txt");
//        String name = file.getName();
//
//        LogUtil.e("文件名：",name+"文件大小："+file.length());


    }

    private void shouJinggao() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContext);
        normalDialog.setTitle("IP端口配置");
        normalDialog.setMessage("点击“继续”您将清除现有的IP端口配置，并需要重新配置IP以及端口，请谨慎操作");
        normalDialog.setPositiveButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                SPUtil.RemoveString(mContext,Constants_SP.SERVER_ADDRESS);
                startActivity(new Intent(mContext,IpSettingActivity.class));
                finish();
            }
        });
        normalDialog.setNegativeButton("返回",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }


    private static Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_UPDATE_DIALOG:
                    break;
                case SHOW_NO_UPDATE_DIALOG:
                    break;
            }
            super.handleMessage(msg);
            //isExit = false;jianguanduao.
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            //mHandler.sendEmptyMessageDelayed(0, 2000);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            //TODO: 2016/6/15 退出时清除登录信息
            //Log.e(TAG, "exit application");
            //IsLogin.isLoin = false;
            MyApplication.getInstance().exitApp();            //System.exit(0);
        }
    }


    /**
     * 是否大陆手机
     *
     * @param str
     * @return
     */
    public static boolean isChinaPhoneLegal(String str) {
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[^4])|(16[6])|(18[0-9])|(17[0,1,3,5,6,7,8])|(19[9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }


    private void initRequsUserData() {
        requestUser = new RequestUser();
        requestUser.setAccessId(editTextName.getText().toString());
        requestUser.setAuthCode(editTextPsw.getText().toString());
        requestUser.setTimeStamp(TimeUtils.getTime());
        requestUser.setMobileType(1);
        mobileToken=SPUtil.getString(this,Constants_SP.XGTOKEN,"");
        if (mobileToken==null||mobileToken.equals("")){
            ToastUtils.show(mContext,"请稍后，Token正在初始化");
            return;
        }
        requestUser.setMobileToken(mobileToken);
        requestUser.setSign(generateSign(requestUser));
    }

    private void initRequSMSData() {
        requestSms = new RequestSms();
        requestSms.setAccessId(editTextName.getText().toString());
        requestSms.setTimeStamp(TimeUtils.getTime());
        requestSms.setSign(generateSign(requestSms));
    }

    private String generateSign(RequestUser req) {
        String result = null;
        StringBuilder sb = new StringBuilder(new StringBuffer(req.getAuthCode()).reverse().toString());
        sb.append("#FF00");
        sb.append(ConstantsXF.APIKEY);
        sb.append("#DCF0");
        sb.append(req.getAccessId());
        sb.append("#0FCD");
        sb.append(req.getTimeStamp());
        sb.append("#0000");
        sb.append(req.getAuthCode());
        sb.append("#00FF");
        result = sb.toString();
        for (int k = 0; k < ConstantsXF.APICOUNT; k++) {
            result = Md5Util.md5Sum(result);
        }
        return result;
    }


    private String generateSign(RequestSms req) {
        String result = null;
        StringBuilder sb = new StringBuilder();
        sb.append("#00FF");
        sb.append(ConstantsXF.APIKEY);
        sb.append("#00AA");
        sb.append(req.getAccessId());
        sb.append("#AA00");
        sb.append(req.getTimeStamp());
        sb.append("#FF00");
        result = sb.toString();
        for (int k = 0; k < ConstantsXF.APICOUNT; k++) {
            result = Md5Util.md5Sum(result);
        }
        return result;
    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void getSms(SmsBean s) {
        LogUtil.e("获取验证码成功", s.getInfo());
        if (s.getResult() == 0) {
            myCountDownTimer.start();
        } else if (s.getResult() == 2) {
            ToastUtils.show(this, "账号密码错误");

        } else {
            ToastUtils.show(this, "验证码获取失败");
        }
        ;
    }

    @Override
    public void getUser(UserBean_W userBean_w) {
        LogUtil.e("请求成功", userBean_w.getDeptName());
        if (userBean_w.getResult() == 0) {
            int unitId = userBean_w.getUnitId();//单位ID
            int deptId = userBean_w.getDeptId();//消防队ID
            String deptName = userBean_w.getDeptName();//消防队名称
            String unitName = userBean_w.getUnitName();//单位名称
            List<String> module = userBean_w.getModule();//功能模块
            String userName = userBean_w.getUserName();//人员名称
            String accessId = editTextName.getText().toString();

            SPUtil.putString(this, Constants_SP.ACCESSID, accessId);
            SPUtil.putString(this, Constants_SP.USERNAME, userName);
            SPUtil.putList(this, Constants_SP.MODULE, module);
            SPUtil.putString(this, Constants_SP.UNITNAME, unitName);
            SPUtil.putInt(this, Constants_SP.UNITID, unitId);
            SPUtil.putInt(this, Constants_SP.DEPID, deptId);
            SPUtil.putString(this, Constants_SP.DEPTNAME, deptName);
            gotoActivity(MainActivity.class, true);
        } else {
            ToastUtils.show(this, userBean_w.getInfo());
        }
    }

    //倒计时函数
    private class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        } //计时过程

        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            timeButton.setClickable(false);
            timeButton.setText(l / 1000 + "秒");
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            timeButton.setText("重新获取");
            // 设置可点击
            timeButton.setClickable(true);
        }
    }
}
